<template>
  <div class="app-container">
    <Find :OriginalFilter="{ static: true }" :formList="formList" @findClicked="findClicked" @Launchform="Launchform" @clickNumber="clickNumber" />
    <div class="container">
      <el-card class="containerCard" shadow="always" :body-style="{ padding: '5' }">
        <div class="containerCardMain">
          <!-- 左 -->
          <div class="containerCardLeft">
            <!-- 左 -->
            <div class="containerCardLeftL">
              <h1 class="containerCardLeftLH1">选择指令</h1>
              <Table :tableData="TableData" :tableHeader="tableHeader" :TableHeight="95" @currentRow="clicktogetdata" />
            </div>
            <!-- 右 -->
            <div class="containerCardLeftR">
              <h1 class="containerCardLeftLH1">选择轮次</h1>
              <Table :tableData="TableData1" :tableHeader="tableHeader2" :TableHeight="95" @currentRow="clicktogetdataT" />
            </div>
          </div>

          <!-- 右 -->
          <div class="containerCardRight" style="width: 80%">
            <Table :tableData="tableData" :summaryData="summaryData" :tableHeader="tableHeader3" summary :TableHeight="70.5" />
          </div>
        </div>

        <PageModule style="margin-top: 8px" :PageData="{ total }" @pageChange="handleSizeChange" @pageSizeChange="handleCurrentChange" />
      </el-card>
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import JMessage from '@/utils/JMessage'
export default defineComponent({
  name: 'AllocationAndAccountingInquiryKa'
})
</script>
<script lang="ts" setup>
import { i18n, Jzhcn } from '@/i18n'
import { ref, onMounted } from 'vue'
import { InstructAllocationAnd, CycleData, SubjectData, DropDownData } from '@/api/GeneralManager/Factoryinquiry/DiscretionaryAccounts'
import type {
  CommandParameter,
  AllocationOfAccountsDto,
  SubjectDataParameter,
  TableMainDto
} from '@/api/GeneralManager/Factoryinquiry/DiscretionaryAccounts'

const formList = ref([
  {
    type: 'input',
    inputPlaceholder: '请输入指令',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入型体',
    inputValue: ''
  },
  {
    type: 'select',
    selectValue: '',
    selectLabel: '部门',
    selectOptions: []
  },
  {
    type: 'input',
    inputLabel: '型体',
    inputDisabled: true,
    inputValue: ''
  },
  {
    type: 'input',
    inputLabel: '颜色',
    inputDisabled: true,
    inputValue: ''
  },
  {
    type: 'input',
    inputLabel: '订单量',
    inputDisabled: true,
    inputValue: ''
  },
  {
    type: 'radio',
    checkboxLabel: '收料状况',
    checked: true,
    label: '1'
  },
  {
    type: 'radio',
    checkboxLabel: '发料状况',
    checked: false,
    label: '2'
  },
  {
    type: 'radio',
    checkboxLabel: '库存状况',
    checked: false,
    label: '3'
  },
  {
    type: 'button',
    checkboxLabel: '置空',
    bgColor: '#1890FF'
  },
  {
    type: 'input',
    inputLabel: '指令生产周期',
    inputDisabled: true,
    inputValue: ''
  }
])

const TableThree = ref<TableMainDto[]>([])

const EvaluatesTheArrayReturnValue = (ArrayList: any) => {
  return ArrayList.map((item: any, index: any) => {
    return {
      optionKey: index,
      optionValue: item,
      optionLabel: item
    }
  })
}

const HeaderFind = async () => {
  const result = await DropDownData()
  const arrayResult = Object.keys(result).map((key) => ({ label: key, value: result[key] }))

  let NewArray = arrayResult.reduce<any>((arr, item) => {
    if (item.label && item.value) {
      // 只添加非空的 typeName 和 typeNo
      arr.push(item.label + ' ' + item.value)
    }
    return arr
  }, [])

  formList.value[2].selectOptions = EvaluatesTheArrayReturnValue(NewArray)
  formList.value[2].selectValue = NewArray[0]
  BodyTableParameter.value.processCode = NewArray[0].split(' ')[1]
}

// 选择指令表格数据
const TableData = ref<AllocationOfAccountsDto[]>()

// 选择轮次表格数据
const TableData1 = ref()

// 总数
const total = ref<number>(0)

const lotNoO = ref<string>('')

const clicktogetdata = (row: any) => {
  const { lotNo, style, color, ordQty, lotCycle } = row || {}
  lotNoO.value = lotNo
  BodyTableParameter.value.lotNo = lotNo
  formList.value[3].inputValue = style
  formList.value[4].inputValue = color
  formList.value[5].inputValue = ordQty
  formList.value[10].inputValue = lotCycle

  GetDepartmentData()
}

const clicktogetdataT = (row?: any) => {
  const { lsNo } = row || {}
  BodyTableParameter.value.lsNo = lsNo
  SubjectTableData()
}

const BodyTableParameter = ref<SubjectDataParameter>({
  lotNo: '',
  lsNo: 0,
  mtlCode: formList.value[6].label!,
  processCode: ''
})

interface summaryDataType {
  index: number
  num: number | undefined
}

// 计算金额总数
const summaryData = ref<summaryDataType[]>()

const SubjectTableData = async () => {
  const result = await SubjectData(BodyTableParameter.value)

  TableThree.value = result.dto

  console.log(result, '+++++++++')

  /// 填充 summaryData
  const supportTotal = result.supportTotal

  // 获取 supportTotal 中除 total 以外的键，并将它们按升序排列
  const supportKeys = Object.keys(supportTotal)
    .filter((key) => key !== 'total')
    .map((key) => parseFloat(key))
    .filter((key) => !isNaN(key))
    .sort((a, b) => a - b)

  // 根据索引数组生成 summaryData
  const summaryDataValue = supportKeys.map((key, index) => ({
    index: index === 0 ? 2 : index + 3, // 使用 index + 3 来保持递增索引
    num: supportTotal[key.toString()]
  }))

  // 对大于2的 index 进行减法操作
  summaryDataValue.forEach((item) => {
    console.log(item)
    if (item.index === 4 || item.index > 4) {
      item.index = item.index + 2
    } else {
      item.index = 5
    }
  })

  // 将 total 键对应的值放到下标为2的元素
  summaryDataValue.splice(1, 0, {
    index: 2,
    num: supportTotal.total
  })

  // 将 summaryData 值设置为生成的数组
  summaryData.value = summaryDataValue

  // 输出生成的 summaryData
  console.log(summaryData.value)

  // 清空动态表头数据
  tableHeader3.value = []

  // 添加固定的列到表头
  tableHeader3.value.push(
    {
      label: '部位',
      prop: 'partName',
      width: '112px'
    },
    {
      label: '裁次',
      prop: 'cutSeq',
      width: '112px'
    },
    {
      label: '合计(欠数/已制)',
      prop: 'total',
      width: '112px'
    },
    {
      label: '派工日期',
      prop: 'department',
      width: '112px'
    },
    {
      label: '采集日期',
      prop: 'date',
      width: '112px'
    }
  )

  // 动态构建表头数据
  const allQtyArrays = result.dto.map((item: any) => {
    return Object.entries(item.qty).map(([size, value]) => ({ size, value }))
  })

  allQtyArrays.forEach((item: any) => {
    item.forEach((item1: any) => {
      const existingColumn = tableHeader3.value.find((column) => column.prop === item1.size)
      if (!existingColumn) {
        tableHeader3.value.push({
          label: item1.size,
          prop: item1.size,
          width: ''
        })
      }
    })
  })

  // 将动态生成的列与表体数据进行映射
  TableThree.value.forEach((row) => {
    allQtyArrays.forEach((item: any) => {
      item.forEach((item1: any) => {
        const sizeProp = item1.size as keyof typeof row // 使用类型断言
        ;(row[sizeProp] as any) = row.qty[item1.size] || '' // 将qty中的值赋给相应的动态列
      })
    })
  })

  // 更新表格数据
  tableData.value = TableThree.value
}

// 需要收集的数据
const dataCollection = ref<CommandParameter>({
  lotNo: '',
  pageNum: 1,
  pageSize: 40,
  style: ''
})

// 选择指令数据
const ConsumableTableData = async () => {
  const result = await InstructAllocationAnd(dataCollection.value)
  TableData.value = result.dto
  total.value = result.total
  // 使用短路逻辑处理可能为 undefined 的属性
  lotNoO.value = result.dto[0]?.lotNo || ''
  BodyTableParameter.value.lotNo = result.dto[0]?.lotNo || ''
  if (formList.value[3].inputValue === '') {
    formList.value[3].inputValue = result.dto[0]?.style || ''
    formList.value[4].inputValue = result.dto[0]?.color || ''
    formList.value[5].inputValue = (result.dto[0]?.ordQty as any) || ''
    formList.value[10].inputValue = result.dto[0]?.lotCycle || ''
  }
  if (BodyTableParameter.value.lotNo !== '') {
    GetDepartmentData()
  }
}

const native = ref(false)

// 轮次
const GetDepartmentData = async () => {
  const result = await CycleData(lotNoO.value)
  TableData1.value = result.map((item: any) => {
    return { lsNo: item }
  })
  BodyTableParameter.value.lsNo = TableData1.value[0].lsNo
  SubjectTableData()
}

// 统一调用接口
const interAceFunct = () => {
  // 选择指令数据
  ConsumableTableData()

  // 部门下拉框数据
  HeaderFind()
}

onMounted(() => {
  interAceFunct()
})

const tableData = ref()

const tableHeader = ref([
  {
    label: '指令',
    prop: 'lotNo',
    width: '112px'
  }
])

const tableHeader2 = ref([
  {
    label: '轮次',
    prop: 'lsNo',
    width: '112px'
  }
])

const tableHeader3 = ref([
  {
    label: '部位',
    prop: 'partName',
    width: '112px'
  },
  {
    label: '裁次',
    prop: 'cutSeq',
    width: '112px'
  },
  {
    label: '合计(欠数/已制)',
    prop: 'total',
    width: '112px'
  },
  {
    label: '派工日期',
    prop: 'department',
    width: '112px'
  },
  {
    label: '采集日期',
    prop: 'date',
    width: '112px'
  }
])

const handleSizeChange = (val: number) => {
  dataCollection.value.pageNum = val
  ConsumableTableData()
}
const handleCurrentChange = (val: number) => {
  dataCollection.value.pageSize = val
  ConsumableTableData()
}

const Launchform = (val: any) => {
  console.log(val[0].inputValue)
  BodyTableParameter.value.processCode = val[2].selectValue?.split(' ')[1]?.trim()
  dataCollection.value.lotNo = val[0].inputValue
  dataCollection.value.style = val[1].inputValue
  ConsumableTableData()
}

const findClicked = (find: any) => {
  if (find === '置空') {
    clearFormList1()
  }
}

const clearFormList1 = () => {
  formList.value.forEach((item) => {
    if (item.type === 'input') {
      item.inputValue = ''
    }
  })
}

const clickNumber = (val: any) => {
  BodyTableParameter.value.mtlCode = val
  SubjectTableData()
}
</script>

<style lang="less" scoped>
.container {
  margin-top: 12px;
}

.containerCardLeft {
  height: 630px;
  display: flex;
}

// 卡片
.containerCard {
  width: 100%;
  box-shadow: none;

  .containerCardMain {
    width: 100%;
    display: flex;
    width: 100%;
  }
}

.containerCardRight {
  margin-left: 30px;
  margin-top: 20px;
}

.containerCardLeftR {
  margin-left: 30px;
}

h1 {
  font-size: 16px;
}
</style>
